﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class Friendly : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.Friendly_PagePageTitle;
            // security part
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                Response.Redirect("~/Default.aspx");

            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            //this.Title = Resources.Resource.Friendly_PageTitle + " - " + GND.ReturnAppTitle();

            TeamIdHiddenField.Value = ou.TeamId;
            if (ou.TeamId == "Null")
                Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");

            if (Request.QueryString["Message"] != null)
                this.MessageLabel.Text = Request.QueryString["Message"];
            
            if (!IsPostBack)
            {
                //this.ScheduledFriendlyGamesDataSourse.SelectParameters.Add("UserId", UserId);
                this.SuggestionsDataSourse.SelectParameters.Add("UserId", ou.UserId);
                this.SuggestionsDataSourse.SelectParameters.Add("IsNT", "0");
                this.ChallangesDataSourse.SelectParameters.Add("UserId", ou.UserId);
                this.ChallangesDataSourse.SelectParameters.Add("IsNT", "0");
                this.FriendlyWeeksDataSource.SelectParameters.Add("TeamId", ou.TeamId);
                this.FriendlyPoolUpdatePanel.Visible = ou.IsPremium;
                
                
                if (ou.IsPremium)
                {
                    this.LeaguesDDL.Items.Add(new ListItem(Resources.Resource.Friendly_NotHigherThan + " " + Resources.Resource.Global_Level + " 2", "2"));
                    this.LeaguesDDL.Items.Add(new ListItem(Resources.Resource.Friendly_NotHigherThan + " " + Resources.Resource.Global_Level + " 3", "3"));
                    this.LeaguesDDL.Items.Add(new ListItem(Resources.Resource.Friendly_NotHigherThan + " " + Resources.Resource.Global_Level + " 4", "4"));
                    this.LeaguesDDL.Items.Add(new ListItem(Resources.Resource.Friendly_NotHigherThan + " " + Resources.Resource.Global_Level + " 5", "5"));
                    this.LeaguesDDL.Items.Add(new ListItem(Resources.Resource.Friendly_NotHigherThan + " " + Resources.Resource.Global_Level + " 6", "6"));
                }
                StadiumsDDLDataSource.SelectParameters.Add("UserId", ou.UserId);
                JoinedFriendlyPoolDataSource.SelectParameters.Add("TeamId", ou.TeamId);
                ExistingFriendlyPoolSuggestions.SelectParameters.Add("UserId", ou.UserId);
                FriendlyGetAllTeamFriendlyMatchesDataSource.SelectParameters.Add("TeamId", ou.TeamId);

                InitFriendlyPoolArea();

                // deal with niewbie tips
                if (!IsPostBack)
                {
                    if ((int)Session["NewbieTipStage"] == 7)
                    {
                        Session["NewbieTipStage"] = 8;
                        Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", "8", ou.Language);
                        GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "8");
                    }
                }
            }
            this.MessagePanel.Visible = (this.MessageLabel.Text.Length > 0);
            
            IncomingChallangesPanel.Visible = (IncomingChallangesGridView.Rows.Count > 0);
            OutgoingChallangesPanel.Visible = (OutgoingFriendlyChallangesGridView.Rows.Count > 0);
            ExistingSuggestionsPanel.Visible = (ExistingSuggestionsGridview.Rows.Count > 0);
            ScheduledMatchesPanel.Visible = (ScheduledMatchedGridvew.Rows.Count > 0);
            
        }

        protected void IncomingFriendlyRowCommand(object sender, GridViewCommandEventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            if (e.CommandName == "Decline")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                string Answer = GND.ReadNivdalStringData("ChallangeId", "Language", "Nivdal_FriendlyDeclineFriendlyChalange", e.CommandArgument, ou.Language);
                MessagePanel.Visible = true;
                MessageLabel.Text = Answer;
            }
            else if (e.CommandName == "Accept")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                string Answer = GND.ReadNivdalStringData("ChallangeId", "Language", "Nivdal_FriendlyAcceptFriendlyChallange", e.CommandArgument, ou.Language);
                MessagePanel.Visible = true;
                MessageLabel.Text = Answer;
            }
            RefreshAll();
        }

        protected void WithdrawFriendly(object sender, GridViewCommandEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string Answer = GND.ReadNivdalStringData("ChallangeId", "Language", "Nivdal_FriendlyDeleteFriendlyChalange", e.CommandArgument, ou.Language);
            MessagePanel.Visible = true;
            MessageLabel.Text = Answer; 
            RefreshAll();
        }

        protected string WithdrawChallangeOnClientClick(string TeamName)
        {
            return ("return confirm('" + Resources.Resource.Friendly_AreYouSureWithdrawFriendlyConfirm + " " + TeamName + " ?')");
        }

        protected string DeclineChallangeOnClientClick(string TeamName)
        {
            return ("return confirm('" + Resources.Resource.Friendly_AreYouSureDeclineFriendlyConfirm + " " + TeamName + " ?')");
        }

        protected string AcceptChallangeOnClientClick(string TeamName)
        {
            return ("return confirm('" + Resources.Resource.Friendly_AreYouSureAcceptFriendlyConfirm + " " + TeamName + " ?')");
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        

        protected string FormatWeekDate(object Time)
        {
            string returnValue = "";
            try
            {
                returnValue = string.Format("{0:d}", Time);
            }
            catch { returnValue = "error"; }

            return returnValue;
        }

        protected string FormatMatchTime(object Time)
        {
            string returnValue = "";
            try
            {
                returnValue = string.Format("{0:f}", Time);
            }
            catch { returnValue = "error"; }

            return returnValue;
        }

        protected string GetDatesString(object startDate, object EndDate)
        {
            return (Resources.Resource.Friendly_FriendlyWeekTitle + " " + startDate.ToString() + " - " + EndDate.ToString());

        }

        protected void GamesGridViewRowCommand(object sender, GridViewCommandEventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string Answer;
            if ((e.CommandName == "AcceptCancel") || (e.CommandName == "Suggest"))
            {
                Answer = GND.ReadNivdalStringData("MatchId", "TeamId", "Nivdal_FriendlySuggestToCancel", e.CommandArgument, TeamIdHiddenField.Value);
            }
            else if (e.CommandName == "DeclineCancel")
            {
                Answer = GND.ReadNivdalStringData("SuggestionId", "TeamId", "Nivdal_FriendlyDeclineCancelSuggestion", e.CommandArgument, TeamIdHiddenField.Value);
            }

            RefreshAll();
        }

        protected void RefreshAll()
        {
            Response.Redirect("~/Friendly.aspx");
            //IncomingChallangesGridView.DataBind();
            //OutgoingFriendlyChallangesGridView.DataBind();
            ////FriendlyWeeksRepeater.DataBind();
            //foreach (RepeaterItem i in FriendlyWeeksRepeater.Items)
            //{
            //    (i.FindControl("GamesGridView") as GridView).DataBind();
            //}
        }

        //protected void AddTeamIdParam(object sender, RepeaterItemEventArgs e)
        //{
        //    (e.Item.FindControl("FriendlyWeekMatchesDataSource") as SqlDataSource).SelectParameters.Add("TeamId", TeamIdHiddenField.Value);
        //}

        protected void JoinFrienldyPool(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("Nivdal_FriendlyPoolAddTeamToThePool", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("TeamId", SqlDbType.Decimal, 12);
                cmd.Parameters["TeamId"].Value = ou.TeamId;

                cmd.Parameters.Add("Venue", SqlDbType.Decimal, 1);
                cmd.Parameters["Venue"].Value = VenueDDL.SelectedValue;

                cmd.Parameters.Add("International", SqlDbType.Decimal, 1);
                cmd.Parameters["International"].Value = InternationalDDL.SelectedValue;

                cmd.Parameters.Add("GameRules", SqlDbType.Decimal, 1);
                cmd.Parameters["GameRules"].Value = GameRulesDDL.SelectedValue;

                cmd.Parameters.Add("LeagueLevel", SqlDbType.Decimal, 1);
                cmd.Parameters["LeagueLevel"].Value = LeaguesDDL.SelectedValue;

                if (StartDateTextBox.Text.Length > 1)
                {
                    DateTime StartTime;
                    if (DateTime.TryParse(StartDateTextBox.Text, CultureInfo.CreateSpecificCulture("he-HE"), DateTimeStyles.None, out StartTime))
                    {
                        string SQLStartTime = StartTime.Year.ToString() + "-" + StartTime.Month.ToString() + "-" +
                                              StartTime.Day.ToString() + " " + StartDateHoursDDL.SelectedValue + ":" +
                                              StartTimeMinutesDDL.SelectedValue;
                        cmd.Parameters.Add("StartTime", SqlDbType.SmallDateTime);
                        cmd.Parameters["StartTime"].Value = SQLStartTime;
                    }
                }

                if (EndDateTextBox.Text.Length > 2)
                {
                    DateTime EndTime;
                    if (DateTime.TryParse(EndDateTextBox.Text, CultureInfo.CreateSpecificCulture("he-HE"), DateTimeStyles.None, out EndTime))
                    {
                        string SQLEndTime = EndTime.Year.ToString() + "-" + EndTime.Month.ToString() + "-" +
                                              EndTime.Day.ToString() + " " + EndDateHoursDDL.SelectedValue + ":" +
                                              EndTimeMinutesDDL.SelectedValue;
                        cmd.Parameters.Add("EndTime", SqlDbType.SmallDateTime);
                        cmd.Parameters["EndTime"].Value = SQLEndTime;
                    }
                }

                cmd.Parameters.Add("Answer", SqlDbType.NVarChar, 128);
                cmd.Parameters["Answer"].Direction = ParameterDirection.Output;
                
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    Response.Redirect("~/Friendly.aspx");
                }
                finally
                {
                    conn.Close();
                }
                
            }
            
        }

        protected void InitFriendlyPoolArea()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            if (GND.ReadNivdalBoolData("TeamId", "Nivdal_FriendlyCanTeamPlayFriendlies", ou.TeamId))
            {
                if (GND.ReadNivdalBoolData("TeamId", "Nivdal_FriendlyPoolDidTeamJoin", ou.TeamId))
                {
                    JoinFriendlyPoolPanel.Visible = false;                    
                }
                else
                {                    
                    JoinedFriendlyPoolPanel.Visible = false;
                }

            }
            else
            {
                FriendlyPoolUpdatePanel.Visible = false;
            }
        }

        protected string VenueString(object Venue)
        {
            string ReturnValue;
            switch (Venue.ToString())
            { 
                case "1":
                    ReturnValue = Resources.Resource.Friendly_VenueHome;
                    break;
                case "2":
                    ReturnValue = Resources.Resource.Friendly_VenueAway;
                    break;
                default:
                    ReturnValue = Resources.Resource.Friendly_DontCare;
                    break;
            }
            return ReturnValue;
        }

        protected string InternationalString(object International)
        {
            string ReturnValue;
            switch (International.ToString())
            {
                case "1":
                    ReturnValue = Resources.Resource.Friendly_National;
                    break;
                case "2":
                    ReturnValue = Resources.Resource.Friendly_International;
                    break;
                default:
                    ReturnValue = Resources.Resource.Friendly_DontCare;
                    break;
            }
            return ReturnValue;
        }

        protected string RulesString(object Rules)
        {
            string ReturnValue;
            switch (Rules.ToString())
            {
                case "1":
                    ReturnValue = Resources.Resource.Friendly_GameRulesRegular;
                    break;
                case "2":
                    ReturnValue = Resources.Resource.Friendly_GameRulesCup;
                    break;
                default:
                    ReturnValue = Resources.Resource.Friendly_DontCare;
                    break;
            }
            return ReturnValue;
        }

        protected string MaxLeagueLevel(object Level)
        {
            string ReturnValue = Level.ToString();
            if (ReturnValue == "0")
                return (Resources.Resource.Friendly_DontCare);
            return (Resources.Resource.Friendly_NotHigherThan + " " + Resources.Resource.Global_Level + " " + ReturnValue);
        }

        protected void AssignStadium(object sender, EventArgs e)
        {
            string StadiumId = (JoinedFriendlyPoolFormView.FindControl("StadiumsDDL") as DropDownList).SelectedValue;
            string MatchId = (JoinedFriendlyPoolFormView.FindControl("MatchIdHiddenField") as HiddenField).Value;
            if (StadiumId != "0")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];

                if (GND.ReadNivdalBoolData("StadiumId", "MatchId", "TeamId", "Nivdal_FriendlyPoolAssignStadium", StadiumId, MatchId, ou.TeamId))
                    Response.Redirect("~/Friendly.aspx?Message=" + Resources.Resource.Friendly_StadiumAssigned);
                else
                    Response.Redirect("~/Friendly.aspx?Message=" + Resources.Resource.Friendly_CannotAssignStadium);


                //if (GND.ReadNivdalBoolData("StadiumId", "TeamId", "Nivdal_FriendlyPoolAssignStadium", StadiumId, ou.TeamId))
                //    Response.Redirect("~/Friendly.aspx?Message=" + Resources.Resource.Friendly_StadiumAssigned);
                //else
                //    Response.Redirect("~/ListOfTeamMatches.aspx?ConfirmNote=" + 
            }
        }

        protected void LeaveFriendlyPool(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            GND.ExecNivdalSQL("UserId", "Nivdal_FriendlyPoolLeavePool", ou.UserId);

            Response.Redirect("~/Friendly.aspx");
        }

        protected string InstructionsImage(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1")
                return ("~/Images/Icons/add Instructions.gif");
            if (InstructionsNeeded.ToString() == "2")
                return ("~/Images/Icons/edit Instructions.png");
            return "";
        }

        protected string InstructionsToolTip(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1")
                return (Resources.Resource.MatchPage_AssignInstructions);
            if (InstructionsNeeded.ToString() == "2")
                return (Resources.Resource.MatchPage_EditInstructions);
            return "";
        }


        protected void AcceptFriendlyPoolSuggestion(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Accept")
            {
                OnlineUser ou = (OnlineUser)Session["User"];
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

                string Answer = GND.ReadNivdalStringData("FriendlyPoolId", "UserId", "Language", "Nivdal_FriendlyPoolAcceptOffer", e.CommandArgument.ToString(), ou.UserId, ou.Language);
                Response.Redirect("~/Friendly.aspx?Message=" + Answer);
            }
        }

    }
}